home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1841 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: isis.interpac.net!stacys
  2. From: stacys@isis.interpac.net (Stacy Sherman)
  3. Newsgroups: comp.lang.c
  4. Subject: Newbie question:  Is this code OK?
  5. Date: 17 Jan 1996 07:41:58 GMT
  6. Organization: Inter-Pacific Networks
  7. Message-ID: <4di986$fk1@pegasus.interpac.net>
  8. NNTP-Posting-Host: isis.interpac.net
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. I'm learning C and would like to know your opinions on my answer to an 
  12. exercise.  I was supposed to write a function that counts the number of 
  13. words in a string (array of char in this case, with the length specified 
  14. in  a variable).  Of course the biggest problem is stripping out all the 
  15. extraneous white space that may be there.  In this exercise, whitespace 
  16. separating words was either a space, tab or newline character.
  17.  
  18. The code I wrote worked on every case I gave it but I want to know if it 
  19. was well written.  Specifically:
  20.  
  21. I know it's usually not a good idea to increment a loop counter within a 
  22. loop, but I have 2 nested loops using the same counter.  Was this a bad 
  23. thing to do?
  24.  
  25. I have an if statement and a for loop that test for the same things.  Is 
  26. it possible to somehow combine these into one statement?  I couldn't 
  27. think of a way to do it.  
  28.  
  29. Do I need the empty {} after a for loop that has no body?  I assumed if I 
  30. didn't, the loop would execute the next statement after it.  
  31.  
  32. Any other comments?  Here's the code:
  33.  
  34. int words (char string[80], int length)
  35. {
  36.     int i, num_words = 0;
  37.     
  38.     for (i=0; i<length; i++)
  39.     {                /* if char isn't whitespace */
  40.         if ((string[i]!='\n') && 
  41.             (string[i]!='\t') &&
  42.             (string[i]!=' '))
  43.         {
  44.             num_words++;        /* Increment num_words */
  45.             for (; i<length, ((string[i]!='\n') &&
  46.                 (string[i]!='\t') &&   
  47.                 (string[i]!=' ')); i++) 
  48.                  /* and skip past any other */
  49.                  /* chars that may be there */
  50.             { }    /* loop does all work, nothing inside body */
  51.         }
  52.     }
  53.     return (num_words);
  54. }
  55.